package servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.ItemAttr;
import pojo.PollAttr;
import util.Helper;
import dao.ItemDao;
import dao.PollDao;

public class Poll extends ServletTemplate{

    /**
     * 执行POST操作 
     */
    public void doPost(HttpServletRequest request,
                         HttpServletResponse response) throws IOException, ServletException{
        super.doPost(request, response);
        
        if(false == this.isLogin()) {
            this.setRequestAttr("errorInfo", "非法登陆！");
            this.forward("hint.jsp");
            return ;
        }
        
        PollAttr pollAttr       = this.genPollAttr();
        String validateResult   = pollAttr.validate(); 
        if(validateResult != null) {
            this.setRequestAttr("errorInfo", validateResult);
            this.forward("hint.jsp");
            return ;
        }
        
        PollDao pollDao     = new PollDao();
        if(pollDao.isPoll(pollAttr.getUserId())) {
            this.setRequestAttr("hintInfo", "你已经投过票了!");
            this.forward("hint.jsp");
            return;
        }
        if(pollDao.insert(pollAttr)) {
            ItemDao itemDao     = new ItemDao();
            if(true == itemDao.updatePoll(pollAttr.getItemId())) {
                this.setRequestAttr("hintInfo", "投票成功!");
            } else {
                pollDao.delete(pollAttr.getUserId(), pollAttr.getItemId());
                this.setRequestAttr("hintInfo", "投票失败，请重试!");
            }
        } else {
            this.setRequestAttr("hintInfo", "投票失败，请重试!");
        }
        this.forward("hint.jsp");
    }
    
    private PollAttr genPollAttr() {
        PollAttr pollAttr   = new PollAttr();
        pollAttr.setUserId(Helper.obj2Int(this.getRequestParam("user_id")));
        pollAttr.setItemId(Helper.obj2Int(this.getRequestParam("item_id")));
        pollAttr.setCreateTime(Helper.getNowTime());
        
        return pollAttr;
    }
    
}
